<template>
  <!-- 页面-菜单管理-添加 -->
  <div class="sidelip-box">
    <Form
      :model="modelForm"
      ref="menuForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="95"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="menuCode" :label="$t('module.menu.menuCode')">
            <Input
              placeholder
              
              v-model.trim="modelForm.menuCode"
              style="width:100%"
              :disabled="menuId != ''"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="menuName" :label="$t('module.menu.menuName')">
            <Input
              placeholder
              
              v-model.trim="modelForm.menuName"
              :maxlength="50"
              style="width:100%"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="menuType" :label="$t('module.menu.menuType')">
            <Select v-model="modelForm.menuType" style="width:100%" >
              <Option
                v-for="menuType in menuTypeList"
                :value="menuType.vsiKey"
                :key="menuType.vsiKey"
              >
                {{
                menuType.vsiValue
                }}
              </Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status') ">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="effectBegin" :label="$t('module.menu.effectBeginTime')">
            <DatePicker
              type="date"
              ref="effectBegin"
              :placeholder="$t('module.menu.selectDate')"
              :value="modelForm.effectBegin"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="effectEnd" :label="$t('module.menu.effectEndTime')">
            <DatePicker
              type="date"
              ref="effectEnd"
              :placeholder="$t('module.menu.permanent')"
              :value="modelForm.effectEnd"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <!-- 备注 改为 描述 -->
      <Form-item :label="$t('common.describe')">
        <Input
          placeholder
          type="textarea"
          :rows="4"
          
          v-model="modelForm.remark"
          :maxlength="100"
          style="width:100%"
        ></Input>
      </Form-item>
    </Form>
  </div>
</template>
<script>
import valueSetAPI from "@/api/valueSetAPI.js";
import menuAPI from "@/api/menuAPI.js";
import locales from "./locales.js";
import { codeReg } from "@/const.js";

// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  name: "menu-edit",
  mixins: [locales],
  components: {},
  props: {
    menuId: {
      type: String,
      default() {
        return "";
      }
    },
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    rowList: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const validateMenuCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.menu.warning.enterMenuCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    return {
      modelForm: {
        menuName: "",
        remark: "",
        id: "",
        effectBegin: "",
        effectEnd: "",
        // effectDate: [],
        menuCode: "",
        menuType: 1,
        tenantCode: null,
        enabled: 1
      },
      rule: {
        menuCode: [{ validator: validateMenuCode, trigger: "blur", required: true }],
        menuName: [
          {
            required: true,
            message: this.$t("module.menu.warning.enterMenuName"),
            trigger: "blur"
          }
        ],
        menuType: [
          {
            required: true,
            message: this.$t("module.menu.warning.enterMenuType"),
            trigger: "change"
          }
        ],
        effectBegin: [{ required: true, type: "string", trigger: "change" }],
        effectEnd: [{ required: true, type: "string", trigger: "change" }]
      },
      menuTypeList: [],
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.effectEnd == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.modelForm.effectEnd.valueOf() - ONE_DAY
            );
          } else if (typeof _this.modelForm.effectEnd == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.effectEnd.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.effectBegin == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.modelForm.effectBegin.valueOf() - ONE_DAY;
          } else if (typeof _this.modelForm.effectBegin == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.effectBegin.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created: function() {
    if (this.menuId) {
      this.$emit("SetTitle", this.$t("module.menu.editMenu"));
    } else {
      this.$emit("SetTitle", this.$t("module.menu.createMenu"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
    // this.queryMenu();
  },
  mounted: function() {
    this.init();
  },
  methods: {
    init() {
      if (this.menuId) {
        this.modelForm = Object.assign({}, this.rowList, {
          effectBegin: this.formatDateTime(this.rowList.effectBegin),
          effectEnd: this.rowList.effectEnd == null ? "" : this.formatDateTime(this.rowList.effectEnd)
        });
      } else {
        // 默认有效期
        // this.modelForm.effectBegin = this.formatDateTime(new Date()).trim();
        this.modelForm.effectBegin = new Date()
          .toISOString()
          .replace(/T.*/, " ")
          .trim();
        this.modelForm.effectEnd = "2099-12-31";
      }
      this.initTenant();
      this.initMenuType();
    },
    save() {
      this.$refs["menuForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.modelForm.id) {
            let param = this.modelForm;
            menuAPI
              .updateMenu(param)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.menu.warning.updateSuccessfully"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            let param = this.modelForm;
            menuAPI
              .addMenu(param)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.menu.warning.createMenuSuccessfully"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
        }
      });
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },
    onStartDateChange(date) {
      this.modelForm.effectBegin = date;
    },
    onEndDateChange(date) {
      this.modelForm.effectEnd = date;
    },
    // 初始化所属租户
    initTenant() {
      // 新增菜单时
      if (this.menuId == "" && this.tenantCode) {
        this.modelForm.tenantCode = this.tenantCode;
      }
    },
    // 初始化菜单类型
    initMenuType() {
      valueSetAPI.getValueSetByCode("SYS_MENU_TYPE").then(data => {
        this.menuTypeList = data;
      });
    }
  }
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}
.ivu-form .ivu-form-item-label {
  padding: 10px 9px 10px 0 !important;
}
</style>
